package config

import (
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/plugin/dbresolver"
	"project/internal/database/gorms"
)

var _db *gorm.DB

func (c *Config) ReConnMysql() {
	// 开启读写分离
	switch c.Dc.Separation {
	case true:
		// master
		masterUsername := c.Dc.Master.Username // 账号
		masterPassword := c.Dc.Master.Password // 密码
		masterHost := c.Dc.Master.Host         // 数据库地址，可以是IP或域名
		masterPort := c.Dc.Master.Port
		masterDbname := c.Dc.Master.Db
		masterDns := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
			masterUsername, masterPassword, masterHost, masterPort, masterDbname)
		var err error
		// 连接Mysql数据库
		_db, err = gorm.Open(mysql.Open(masterDns), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Info),
		})
		if err != nil {
			zap.L().Error("Use master err: ", zap.Error(err))
		}
		// slave
		var replicas []gorm.Dialector
		for _, v := range c.Dc.Slave {
			username := v.Username
			password := &v.Password
			host := v.Host
			port := v.Port
			dbname := v.Db
			slaveDns := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
				username, password, host, port, dbname)
			cfg := mysql.Config{
				DSN: slaveDns,
			}

			replicas = append(replicas, mysql.New(cfg))
		}
		// 读写分离
		_db.Use(dbresolver.Register(dbresolver.Config{
			Sources:  []gorm.Dialector{mysql.Open(masterDns)}, // 或者 ysql.New(mysql.config{DSN:master_dsn})
			Replicas: replicas,
			Policy:   dbresolver.RandomPolicy{}, // 策略 随机
		}).SetMaxOpenConns(200).SetMaxIdleConns(10)) // 设置连接池最大连接数，空闲连接数10
	default:
		// 未启用读写分离
		// 配置Mysql连接参数
		useername := c.Mc.Username
		password := c.Mc.Password
		host := c.Mc.Host
		port := c.Mc.Port
		dbname := c.Mc.Db
		masterDns := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", useername, password, host, port, dbname)
		var err error
		// 连接Mysql数据库
		_db, err = gorm.Open(mysql.Open(masterDns), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Info),
		})

		if err != nil {
			zap.L().Error("use slave err: ", zap.Error(err))
		}
	}
	// 设置config._db == gorm._db 绕过不到处的设定
	gorms.SetDB(_db)
}
